package cn.feuler.user8080.controller;

import cn.feuler.common.entity.Token;
import cn.feuler.common.entity.User;
import cn.feuler.user8080.client.CodeClient;
import cn.feuler.user8080.service.TokenService;
import cn.feuler.user8080.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {

    private final UserService userService;
    private final CodeClient codeClient;
    private final TokenService tokenService;

    @Autowired
    public UserController(UserService userService, CodeClient codeClient, TokenService tokenService) {
        this.userService = userService;
        this.codeClient = codeClient;
        this.tokenService = tokenService;
    }

    @PostMapping("register")
    public Object register(HttpServletResponse response,
                           String email, String password, String code) {
        System.out.println("start register process of [" + email + "]" + "with code [" + code + "]");
        Integer result = codeClient.validate(email, code);
        if (result == null || result == 1) {
            return "验证码错误";
        } else if (result == 2) {
            return "验证码失效";
        }

        if (userService.register(email, password) != null) {
            Token token = tokenService.save(email);
            addCookie(response, "token", token.getToken());
            addCookie(response, "email", email);
            return true;
        } else {
            return false;
        }
    }

    @GetMapping("/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    @PostMapping("/login")
    public String login(HttpServletResponse response,
                        String email, String password) {
        User user = userService.login(email, password);
        if (user != null) {
            Token token = tokenService.save(email);
            addCookie(response, "token", token.getToken());
            addCookie(response, "email", email);
            return user.getEmail();
        } else {
            return null;
        }
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        return tokenService.info(token);
    }

    public void addCookie(HttpServletResponse response, String key, String value) {
        Cookie cookie = new Cookie(key, value);
        cookie.setMaxAge(5 * 60);
        cookie.setPath("/");
        response.addCookie(cookie);
    }

}
